﻿using DevExpress.Mvvm;
using DotNetExtensions.AspNet;
using Habi.Solver.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Habi.Solver.Common
{
    public class ResourceContainer : Singleton<ResourceContainer>
    {
        private ResourceContainer()
        {
            Resources = new Dictionary<long, ResourceModel>();
        }
        public event ResourceEvent OnChanged;
        public event ResourceEvent OnBeforeChange;

        public Dictionary<long, ResourceModel> Resources
        {
            get; private set;
        }

        public void Add(ResourceModel resource)
        {
            if (Resources.ContainsKey(resource.Id)) return;
            OnBeforeChange?.Invoke(resource);
            Resources.Add(resource.Id, resource);
            OnChanged?.Invoke(resource);
        }

        public void Add(IEnumerable<ResourceModel> resources)
        {
            foreach (var item in resources)
            {
                if (Resources.ContainsKey(item.Id)) continue;

                Add(item);
            }
        }


        public void Delete(long id)
        {
            if (!Resources.ContainsKey(id)) return;
            
            var resource = Resources[id];
            OnBeforeChange?.Invoke(resource);
            Delete(resource);
        }

        public void Delete(ResourceModel resource)
        {
            if (!Resources.ContainsKey(resource.Id)) return;

            Resources.Remove(resource.Id);

            OnChanged?.Invoke(resource);
        }

        public void Update(long id, ResourceStatus status)
        {
            if (Resources.ContainsKey(id))
            {
                var resource = Resources[id];
                resource.Status = (int)status;
            }
        }

        public void Reflesh(long id, ResourceStatus status)
        {
            if (Resources.ContainsKey(id))
            {
                var resource = Resources[id];
                resource.Status = (int)status;

                OnChanged?.Invoke(resource);
            }
        }
    }
}